<?php

class SrsUser extends AgaviRbacSecurityUser
{
	private $flash;

	public function setup()
	{
		parent::setup();

		$rd = $this->getContext()->getRequest()->getRequestData();

		$this->grantRole('guest');

		if (!$this->isAuthenticated() && $rd->hasCookie('autologon'))
		{
			$login = $rd->getCookie('autologon');

			try
			{
				$this->login($login['username'], $login['password'], true);
			}
			catch (AgaviSecurityException $e)
			{
				$response = $this->getContext()->getController()->getGlobalResponse();

				$response->setCookie('autologon[username]', false);
				$response->setCookie('autologon[password]', false);
			}
		}
	}

	public function login($username, $password, $isPasswordHashed = false)
	{
		if (!$isPasswordHashed)
		{
			$password = hash('sha256', $password);
		}

		$user = Doctrine_Query::create()->from('User u')->where('u.active=1 AND u.email=? AND u.password=?', array($username, $password))->fetchOne();

		if (!$user)
		{
			throw new AgaviSecurityException('password error');
		}

		$this->setAuthenticated(true);
		$this->grantRole($user->role);
		$this->setAttribute('user', $user);
	}

	public function logout()
	{
		$this->clearCredentials();
		$this->setAuthenticated(false);
	}

	/**
	 * @return User
	 */
	public function getCurrentUser()
	{
		if ($this->isAuthenticated())
		{
			return $this->getAttribute('user');
		}
	}

	public function setFlash($message, $type = 'success')
	{
		$this->setAttribute('flash', array($message, $type));
	}

	public function getFlash()
	{
		if ($this->flash === null)
		{
			$this->flash = $this->getAttribute('flash', null, array());

			$this->removeAttribute('flash');
		}
		
		return $this->flash;
	}

	/**
	 * @return array<string,bool>
	 */
	public function getAvailableRoles()
	{
		$roles = array();

		foreach ($this->definitions as $role => $_)
		{
			if ($role === 'guest') continue;
			
			$roles[$role] = $this->hasRole($role);
		}

		return $roles;
	}
}